﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using ContractManager.BLL.Business;
using ContractManager.Common.Class;
using ContractManager.Common.FormBase;
using System.Windows.Forms;
using ContractManager.Entity;
using DevExpress.XtraEditors;

namespace ContractManager.Lists.Contracts
{
    public partial class FrmInsurancesDetail : XtraFormBase
    {
        #region "Private Variable"
        private readonly BackgroundWorker _loadworker = new BackgroundWorker();
        public List<InsuranceType> LstInsuranceType = new List<InsuranceType>();
        public List<MemberBranch> LstMemberBranch = new List<MemberBranch>();

        public bool SaveClose;
        public bool SaveNew;
        public bool OnlyView;
        public int MasterId;

        #endregion

        #region "Form Construction"
        public FrmInsurancesDetail()
        {
            InitializeComponent();
            ClsVariable.DoubleBuffer(this);
            _loadworker.DoWork += loadworker_DoWork;
            _loadworker.RunWorkerCompleted += loadworker_RunWorkerCompleted;
        }
        #endregion

        #region "Private Method"

        private void BlankForm()
        {
            /*txtInsNo.EditValue = null;
            txtInsDate.EditValue = null;
            txtInsFirm.EditValue = null;
            txtInsPeople.EditValue = null;
            txtInsTypId.EditValue = null;
            txtInsAddress.EditValue = null;
            txtInsContent.EditValue = null;
            txtInsStartDate.EditValue = null;
            txtInsCondition.EditValue = null;
            txtInsEndDate.EditValue = null;
            txtInsAmount.EditValue = null;
            txtMbID.EditValue = null;
            txtCustomField1.EditValue = null;
            txtCustomField2.EditValue = null;
            txtCustomField3.EditValue = null;
            txtCustomField4.EditValue = null;
            txtCustomField5.EditValue = null;
            txtCustomField6.EditValue = null;
            txtCustomField7.EditValue = null;
            txtCustomField8.EditValue = null;
            txtCustomField9.EditValue = null;
            txtCustomField10.EditValue = null;*/
            this.ResetControls();
            txtInsNo.Properties.ReadOnly = MasterId > 0;
        }

        public void GetData()
        {
            if (!_loadworker.IsBusy)
            {
                _loadworker.RunWorkerAsync();
                ClsVariable.SetWaitDialogCaption(string.Format("Nạp danh sách {0}...", Text));
            }
        }


        private void LoadLookupData()
        {
            txtMbID.Properties.DataSource = LstMemberBranch;
            txtMbID.Properties.DisplayMember = "MbName";
            txtMbID.Properties.ValueMember = "MbID";

            txtInsTypId.Properties.DataSource = LstInsuranceType;
            txtInsTypId.Properties.DisplayMember = "InsTypName";
            txtInsTypId.Properties.ValueMember = "InsTypId";

            if (MasterId > 0) GetDetail();
        }

        private void GetDetail()
        {
            var detail = ClsInsurances.SelectByPk(MasterId);
            if (detail != null)
            {
                txtInsNo.EditValue = String.Format("{0}", detail.InsNo);
                txtInsDate.EditValue = detail.InsDate;
                txtInsFirm.EditValue = String.Format("{0}", detail.InsFirm);
                txtInsPeople.EditValue = String.Format("{0}", detail.InsPeople);
                txtInsTypId.EditValue = detail.InsTypId;
                txtInsAddress.EditValue = String.Format("{0}", detail.InsAddress);
                txtInsContent.EditValue = String.Format("{0}", detail.InsContent);
                txtInsStartDate.EditValue = detail.InsStartDate;
                txtInsEndDate.EditValue = detail.InsEndDate;
                txtInsCondition.EditValue = String.Format("{0}", detail.InsCondition);
                txtMbID.EditValue = detail.MbID;
                txtInsAmount.EditValue = detail.InsAmount;

                txtCustomField1.EditValue = String.Format("{0}", detail.CustomField1);
                txtCustomField2.EditValue = String.Format("{0}", detail.CustomField2);
                txtCustomField3.EditValue = String.Format("{0}", detail.CustomField3);
                txtCustomField4.EditValue = String.Format("{0}", detail.CustomField4);
                txtCustomField5.EditValue = String.Format("{0}", detail.CustomField5);
                txtCustomField6.EditValue = String.Format("{0}", detail.CustomField6);
                txtCustomField7.EditValue = String.Format("{0}", detail.CustomField7);
                txtCustomField8.EditValue = String.Format("{0}", detail.CustomField8);
                txtCustomField9.EditValue = String.Format("{0}", detail.CustomField9);
                txtCustomField10.EditValue = String.Format("{0}", detail.CustomField10);  
            } 

        }

        private void DoSave()
        {
           
            #region "Check Condition"
            //if (!FormIsNotValidate)
            //{
            //    if (!dxValidationProvider.Validate())
            //    {
            //        XtraMessageBox.Show(
            //                    "Vui lòng nhập đầy đủ thông tin trước khi lưu",
            //                    "Thông báo",
            //                    MessageBoxButtons.OK,
            //                    MessageBoxIcon.Error);
            //        txtCode.SelectAll();
            //        txtCode.Focus();
            //        return;
            //    }
            //}
            
            #endregion

            var item = MasterId <= 0 ? new Insurances() : ClsInsurances.SelectByPk(MasterId);
            item.InsNo = String.Format("{0}", txtInsNo.EditValue);
            item.InsDate = txtInsDate.DateTime;

            item.InsFirm = String.Format("{0}", txtInsFirm.EditValue);
            item.InsPeople = String.Format("{0}", txtInsPeople.EditValue);
            item.InsTypId = Convert.ToInt32(txtInsTypId.EditValue);
            item.InsAddress = String.Format("{0}", txtInsAddress.EditValue);
            item.InsContent = String.Format("{0}", txtInsContent.EditValue);
            item.InsStartDate = txtInsStartDate.DateTime;
            item.InsEndDate = txtInsEndDate.DateTime;

            item.InsCondition = String.Format("{0}", txtInsCondition.EditValue);
            item.MbID = Convert.ToInt32(txtMbID.EditValue);

            item.InsAmount = Convert.ToDouble(txtInsAmount.EditValue);
            

            item.CustomField1 = String.Format("{0}", txtCustomField1.EditValue);
            item.CustomField2 = String.Format("{0}", txtCustomField2.EditValue);
            item.CustomField3 = String.Format("{0}", txtCustomField3.EditValue);
            item.CustomField4 = String.Format("{0}", txtCustomField4.EditValue);
            item.CustomField5 = String.Format("{0}", txtCustomField5.EditValue);
            item.CustomField6 = String.Format("{0}", txtCustomField6.EditValue);
            item.CustomField7 = String.Format("{0}", txtCustomField7.EditValue);
            item.CustomField8 = String.Format("{0}", txtCustomField8.EditValue);
            item.CustomField9 = String.Format("{0}", txtCustomField9.EditValue);
            item.CustomField10 = String.Format("{0}", txtCustomField10.EditValue);

            item.FormId = FormNo;
            item.VoucherCate = VoucherCate;

            try
            {
                if (MasterId > 0)
                {
                    item.UpdateBy = ClsVariable.EmployeeId;
                    item.UpdateDate = DateTime.Now;
                    ClsInsurances.Update(item); 
                }
                else
                {
                    item.CreateBy = ClsVariable.EmployeeId;
                    item.CreateDate = DateTime.Now;
                    ClsInsurances.Insert(item);
                    MasterId = item.InsId;
                }

                
                if (SaveNew)
                {
                    MasterId = 0;
                    BlankForm();
                    txtInsNo.Focus();
                    
                }
                else if (SaveClose)
                {
                    Close();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(
                    String.Format("Có lỗi xảy ra trong quá trình cập nhật dữ liệu. {0}", ex.Message),
                    "Thông báo",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }
        }

        private void DoDelete()
        {
            if (MasterId <= 0) return;
            
            try
            {
                if (
                        XtraMessageBox.Show(
                                        "Bạn có muốn xóa bản ghi này không?",
                                        "Thông báo",
                                        MessageBoxButtons.YesNo,
                                        MessageBoxIcon.Question) == DialogResult.No) return;
                ClsInsurances.DeleteByPk(MasterId);
                Close();
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(
                       "Có lỗi xảy ra trong quá trình xóa dữ liệu. " + ex.Message,
                       "Thông báo",
                       MessageBoxButtons.OK,
                       MessageBoxIcon.Error);
            }
        }

        #endregion

        #region "Background Worker"

        private void loadworker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                LstInsuranceType = ClsInsuranceType.SelectAll();
                LstMemberBranch = ClsMemberBranch.SelectAll();
                e.Result = LstInsuranceType;
            }
            catch (Exception)
            {
                e.Cancel = true;
            }
        }

        private void loadworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            Action a = LoadLookupData;
            txtInsTypId.Invoke(a);
            ClsVariable.SetWaitDialogCaption(string.Format("Danh sách {0} đã được nạp", Text));
        }
        #endregion

        #region "Form Event"
        private void FrmInsurancesDetailLoad(object sender, EventArgs e)
        {
            BlankForm();
            GetData();
            //if (MasterId > 0) GetDetail();
            btnSaveNew.Enabled = !OnlyView;
            btnSave.Enabled = !OnlyView;
            btnSaveClose.Enabled = !OnlyView;
            btnDelete.Enabled = !OnlyView;
            btnDesign.Enabled = !OnlyView;
            if (!String.IsNullOrEmpty(FormXtraLayoutTemplate))
            {
                var fileLayout = ClsVariable.GetRestoreLayoutFullPath(FormXtraLayoutTemplate);
                layoutControl.RestoreLayoutFromXml(fileLayout);
            }
        }
        #endregion

        #region "Toolbar Event"
        private void TbMenuItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            switch (e.Item.Name)
            {
                case "btnSave":
                    DoSave();
                    break;
                case "btnSaveNew"://Lưu và thêm mới
                    SaveNew = true;
                    DoSave();
                    break;
                case "btnSaveClose"://Lưu và đóng
                    SaveClose = true;
                    DoSave();
                    break;
                case "btnDelete":
                    DoDelete();
                    break;
                case "btnDesign":
                    
                    break;
                case "btnRefresh"://Nạp lại danh mục
                    break;
                case "btnHistory"://History
                    break;
                case "btnClose":
                    Close();
                    break;
            }
        }
        #endregion

        

        
    }
}
